<template>
    <div>
        <template v-if="type !== 'textarea'">
            <div class="el-input-group__prepend" v-if="$slots.prepend">
                <slot name="prepend"></slot>
            </div>
            <input
                ref="input"
                @input="handleInput"
                class="input"
                :disabled="disabled"
                :type="showPassword ? 'password':'text'"
                v-bind="$attrs"
            />
            <div class="el-input-group__prepend" v-if="$slots.prepend">
                <slot name="suffix"></slot>
            </div>
        </template>
        <template v-else>
            <textarea
                v-bind="$attrs"
                ref="textarea"
                :rows="3"
            />
        </template>
       
    </div>
</template>

<script>
    export default {
        name: 'MyInput',
        props: {
            value: [String,Number],
            disabled: {
                type: Boolean,
                default: false
            },
            showPassword: {
                type: Boolean,
                default: false,
            },
            type: {
                type: String,
                default: 'text'
            },

        },
        methods: {
            getInput() {
                return this.$refs.input
            },
            setInputVal() {
                this.getInput();
            },
            handleInput(event) {
                // input的值和初始化传入的值相等 就不需要向组件外传值
                if(event.target.value === this.nativeInputValue) return;
                this.$emit('input',event.target.value)
                // input的值改变后 设置value值
                this.$nextTick(this.setNativeInputValue)
            },
            setNativeInputValue() {
                // 获取到input
                const input = this.getInput();
                if(!input) return;
                if(input.value === this.nativeInputValue) return;
                input.value = this.nativeInputValue;
            },
        },
        computed: {
            nativeInputValue() {
                return this.value === null || this.value === undefined ? '':String(this.value)
            }
        },
        mounted() {
            this.setNativeInputValue()
        }
    }
</script>

<style lang="scss" scoped>
.input {
    height: 28px;
}
</style>